<template>
  <div class="login-section">
    <el-form
      :model="registerForm"
      :rules="registerFormRules"
      ref="registerFormRef"
      label-width="80px"
      size="normal"
    >
      <el-form-item label="用户名" prop="name">
        <el-input
          type="text"
          v-model="registerForm.name"
          prefix-icon="el-icon-s-custom"
        ></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          type="password"
          v-model="registerForm.password"
          prefix-icon="el-icon-lock"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitFrom">注册</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { register } from "@/apis/user.js";
export default {
  name: "Register",
  data() {
    return {
      // 注册用户数据
      registerForm: {
        name: "",
        password: "",
      },
      // 校验规则
      registerFormRules: {
        name: [
          {
            required: true, //规定是必填项
            message: "请填写用户名", //不符合校验条件的提示
            trigger: "blur", //触发条件
          },
          {
            max: 16,
            min: 3,
            message: "长度为3-16个字符",
            trigger: "blur", //触发条件
          },
        ],
        password: [
          {
            required: true,
            message: "请设置密码",
            trigger: "blur",
          },
          {
            // pattern: /^[a-zA-Z0-9]{6-8}$/,
            max: 8,
            min: 6,
            message: "长度为6-8个数字或字母组合",
            trigger: "blur", //触发条件
          },
        ],
      },
    };
  },
  methods: {
    // 点击按钮注册
    submitFrom() {
      this.$refs.registerFormRef.validate(async (valid) => {
        // 判断校验结果 valid
        if (valid) {
          // 通过校验，注册
          // 在这里向后端发送登录用户名和密码
          const res = await register({ ...this.registerForm });
          console.log(res);
          // 判断code是否等于0，等于0注册成功，反之失败
          if (res.code === 0) {
            // 注册成功
            this.$message({
              message: "恭喜你，注册成功，请登录",
              type: "success",
            });
          } else {
            // 注册失败
            this.$message({
              message: res.mes,
              type: "warning",
            });
          }
        } else {
          this.$message.error("注册失败!");
          return false;
        }
      });
    },
    // 点击按钮表单清空重置
    resetForm() {
      this.$refs.registerFormRef.resetFields();
    },
  },
};
</script>

<style lang="stylus" scoped>
.login-section {
  padding: 0px 20px;
}
</style>